/*
 * @Description: orders controller
 * @Author: zhhuan
 * @LastEditTime: 2024-03-28 17:02:01
 */
const Order = require("../models/Order")
const Address = require("../models/Address")
const Product = require("../models/Product")

/**
 * @description:订单创建
 */
async function createOrder(username, data) {
  const {
    addressId,
    shopId,
    shopName,
    isCanceled = false, //订单是否被取消
    products = []
  } = data

  const address = await Address.findById(addressId)
  const pIds = products.map((p) => p.id)
  const productList = await Product.find({
    shopId: shopId,
    _id: {
      $in: pIds
    }
  })
  const productListWidthSales = productList.map((p) => {
    const id = p._id.toString()
    const filterProducts = products.filter((item) => item.id === id)
    if (filterProducts.length === 0) {
      throw new Error("未找到匹配的销售数据")
    }

    return {
      orderSales: filterProducts[0].num,
      product: {
        shopId: p.shopId,
        name: p.name,
        imgUrl: p.imgUrl,
        sales: p.sales,
        price: p.price,
        oldPrice: p.oldPrice
      }
    }
  })

  const newOrder = await Order.create({
    username,
    shopId,
    shopName,
    isCanceled,
    products: productListWidthSales,
    address: {
      username: address.username,
      city: address.city,
      department: address.department,
      houseNumber: address.houseNumber,
      name: address.name,
      phone: address.phone
    }
  })
  return newOrder
}

/**
 * @description:  获取订单列表
 * @param {String} username
 */
async function getOrderList(username) {
  const list = await Order.find({ username }).sort({ _id: -1 })
  return list
}
module.exports = { createOrder, getOrderList }
